package com.moive.news.tqnewsapplication.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Point;
import android.media.ExifInterface;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class ImageUtil {

    /**
     * 根据指定的图像路径和大小来获取缩略图 此方法有两点好处： 1.
     * 使用较小的内存空间，第一次获取的bitmap实际上为null，只是为了读取宽度和高度，
     * 第二次读取的bitmap是根据比例压缩过的图像，第三次读取的bitmap是所要的缩略图。 2.
     * 缩略图对于原图像来讲没有拉伸，这里使用了2.2版本的新工具ThumbnailUtils，使 用这个工具生成的图像不会被拉伸。
     *
     * @param imagePath 图像的路径
     * @param width     指定输出图像的宽度
     * @param height    指定输出图像的高度
     * @return 生成的缩略图
     */
    public static Bitmap getImageThumbnail(String imagePath, int width,
                                           int height) {
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // 获取这个图片的宽和高，注意此处的bitmap为null
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        options.inJustDecodeBounds = false; // 设为 false
        // 计算缩放比
        int h = options.outHeight;
        int w = options.outWidth;
        int beWidth = w / width;
        int beHeight = h / height;
        int be = 1;
        if (beWidth < beHeight) {
            be = beWidth;
        } else {
            be = beHeight;
        }
        if (be <= 0) {
            be = 1;
        }
        options.inSampleSize = be;
        // 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        // 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap;
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    public static Bitmap scaleToScreen(Activity context, Uri uri) {
        Bitmap bitmap = null;
        Point screenSize = new Point();
        // 获取屏幕的大小
        context.getWindowManager().getDefaultDisplay().getSize(screenSize);
        final int width = screenSize.x;// 图片最大宽度
        final int height = screenSize.y - 120;// 图片的最大高度
        try {
            FileInputStream fis = new FileInputStream(getRealPathFromURI(context, uri));
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inPurgeable = true;
            opts.inInputShareable = true;
            opts.inJustDecodeBounds = true;
            opts.inPreferredConfig = Bitmap.Config.RGB_565;
            BitmapFactory.decodeStream(fis, null, opts);
            if (opts.outWidth / width >= 2) {
                opts.inSampleSize = opts.outWidth / width;
            }
            opts.inJustDecodeBounds = false;
            fis.close();
            fis = new FileInputStream(getRealPathFromURI(context, uri));

            bitmap = BitmapFactory.decodeStream(fis, null, opts);

//			int bm_width = bitmap.getWidth();
//			int bm_height = bitmap.getHeight();// 图片的高度
//			float w_f = ((float) width) / bm_width;
//			float h_f = ((float) height) / bm_height;
//			if (w_f >= 1 && h_f >= 1) {
//				return bitmap;
//			}
//			Matrix m = new Matrix();// 2D图形绘制类
//			float f = w_f >= h_f ? h_f : w_f;
//			m.setScale(f, f);// 图片的宽与高的缩放比例
//			return Bitmap.createBitmap(bitmap, 0, 0, bm_width, bm_height, m,
//					false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * Uri转String
     */
    public static String getRealPathFromURI(Activity context, Uri contentUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        @SuppressWarnings("deprecation")
        Cursor cursor = context.managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    /**
     * 通过Base32将Bitmap转换成Base64字符串(JPEG格式)
     *
     * @param bit
     * @return
     */
    public static String Bitmap2StrByBase64(Bitmap bit) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 100, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return ("data:image/jpeg;base64," + Base64.encodeToString(bytes, Base64.DEFAULT));
    }

    /**
     * 通过Base32将Bitmap转换成Base64字符串(PNG格式)
     *
     * @param bit
     * @return
     */
    public static String Base64(Bitmap bit) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.PNG, 100, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return ("data:image/png;base64," + Base64.encodeToString(bytes, Base64.DEFAULT));
    }

    /**
     * 将图片按照某个角度进行旋转
     *
     * @param bm     需要旋转的图片
     * @param degree 旋转角度
     * @return 旋转后的图片
     */
    public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
        Bitmap returnBm = null;

        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }
    /**
     * 读取照片exif信息中的旋转角度
     *
     * @return角度
     */
    public static int readPictureDegree(Uri pictureUri) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(pictureUri + "");
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {

                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

}